package com.ckzp.jfinal.system.controller;

import cn.dsna.util.images.ValidateCode;
import com.ckzp.core.ConfigUtil;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.lc.Aes;
import com.ckzp.core.lc.Md5;
import com.ckzp.core.lc.Pwd;
import com.ckzp.core.model.Datas;
import com.ckzp.core.util.ClientUtil;
import com.ckzp.core.util.JwtUtil;
import com.ckzp.jfinal.base.BaseController;
import com.ckzp.jfinal.form.FormData;
import com.ckzp.jfinal.interceptor.Admins;
import com.ckzp.jfinal.interceptor.Roles;
import com.ckzp.jfinal.system.WebSite;
import com.ckzp.jfinal.system.cache.SysConfigCache;
import com.ckzp.jfinal.system.model.SysUser;
import com.ckzp.jfinal.system.util.LoginUtil;
import com.ckzp.jfinal.system.util.SysOnlineUtil;
import com.jfinal.aop.Clear;


/**
 * 本类为系统登陆类，密码修改类
 * Created by 51594 on 2019/10/21.
 */
public class LoginController extends BaseController {


    @Clear
    public void index() {
        redirect(ConfigUtil.getFullWebAdminLoginPath());
    }

    /**
     * 登陆界面
     */
    @Clear
    public void login() {
        String TestAdmin = ConfigUtil.getProperty("TEST_USER", "");
        String TestPwd = ConfigUtil.getProperty("TEST_PWD", "");
        if (ConfigUtil.isWindows()) {
            setForm(FormData.n().addData("username", TestAdmin).addData("password", TestPwd).addData("vcode", 9999));
        } else {
            setForm(FormData.n().addData("username", TestAdmin).addData("password", TestPwd));
        }
        setAttr("sys_title", SysConfigCache.getConfigValue("sys_title"));
        setAttr("version", SysConfigCache.getConfigValue("version"));
        render("login.html");
    }

    /**
     * 修改密码页面
     */
    @Admins(roles = "login", name = "修改密码页面", log = true)
    public void ChangePwd() {
        setForm(FormData.n().addData("oldpwd", "").addData("newpwd", "").addData("newpwd1", ""));
        // setForm(FormData.n());
        render("ChangePwd.html");
    }


    /**
     * 退出系统
     */
    @Clear
    public void logout() {
        String jwt = WebSite.getJwt(getRequest());
        JwtUtil.JwtPool.AddJwt(jwt);
        WebSite.setJwt(getResponse(), null);
        redirect(ConfigUtil.getFullWebAdminLoginPath());
    }

    /**
     * 验证登陆
     */
    @Clear
    public void ValidateLoginApi() {
        Datas data = getDatas(getParaStr("postdata", ""));
        JsonResult jr = new JsonResult(0);
        String username1 = data.getBaseStr("username");
        String username = Aes.aesDecrypt2(username1);
        if (username.equals(username1)) username = Aes.aesDecrypt(username1);

        boolean vCode = true;//默认验证码通过
        //////////////////////////////验证码/////////////////////////////
        String VALIDATECODE = String.valueOf(getRequest().getSession().getAttribute("VALIDATECODE"));
        if ("|admin|".indexOf("|" + username + "|") > -1 || ConfigUtil.isWindows()) {
            vCode = true;
        } else if (VALIDATECODE != null && VALIDATECODE.length() > 0) {
            if (VALIDATECODE.equals(data.getStr("vercode", "").toUpperCase())) {
            } else {
                jr = new JsonResult(9, "验证码错误");
                vCode = false;
            }
        }
        getRequest().getSession().setAttribute("VALIDATECODE", null);
        /////////////////////////////验证码结束//////////////////
        if (vCode) {
            String password1 = data.getBaseStr("password");
            String password = Aes.aesDecrypt2(password1);
            if (password.equals(password1)) password = Aes.aesDecrypt(password1);
            if (password.length() < 8) {
                jr = new JsonResult(9, "密码必须是8位及以上");
            } else if (!Pwd.match_Aa18(password)) {
                jr = new JsonResult(9, "密码必须是大小写字母数字组合");
            } else {
                String ip = ClientUtil.getIp(getRequest());
                String os = ClientUtil.getClientOS(getRequest());
                String browser = ClientUtil.getClientBrowser(getRequest());
                jr = LoginUtil.getInstance().validateUserPwdJwt(username, password, ip);
                if (jr.getCode() == 0) {
                    String jwt = jr.getExtra();
                    WebSite.setJwt(getResponse(), jwt);
                    getRequest().getSession().setAttribute("VALIDATECODE", null);
                    ////////////////////写登陆日志/////////////////
                    String sessid = JwtUtil.getJwtInfo(jwt).getId();
                    int empid = JwtUtil.getJwtInfo(jwt).getUserid();
                    String loginid = JwtUtil.getJwtInfo(jwt).getUsername();
                    /////////////////////写在线用户////////////////////////
                    SysOnlineUtil.n().saveLogin(sessid, empid, ip, os, browser);//
                }
            }
        }
        /////记录日志
        LoginUtil.n().saveLog(getRequest(), jr.getCode(), jr.getMsg(), username);
        renderJson(jr);
    }

    /**
     * 修改密码Api
     */
    @Admins(roles = "login", name = "修改密码Api", log = true)
    public void ChangePwdApi() {
        Datas data = getDatas(getParaStr("postdata", ""));
        String oldPassword1 = data.getBaseStr("oldPassword", "");//
        String password1 = data.getBaseStr("password");//
        String repassword1 = data.getBaseStr("repassword");//
        String password = Aes.aesDecrypt(password1);
        String oldPassword = Aes.aesDecrypt(oldPassword1);
        String repassword = Aes.aesDecrypt(repassword1);
        if (password.length() < 8) {
            renderJson(JsonResult.getResult(9, "新密码必须是8位及以上-" + password1 + "-"));
        } else if (!Pwd.match_Aa18(password)) {
            renderJson(JsonResult.getResult(9, "新密码必须是大小写字母数字组合"));
        } else if (password.equals(repassword)) {
            String empid = getEmpIdStr();
            if (empid.length() < 3) {
                renderJson(JsonResult.getResult(9, "两次密码不一致"));
            } else {
                SysUser su = SysUser.dao.findById(empid);
                if (su == null) {
                    renderJson(JsonResult.getResult(9, "用户不存在"));
                } else {
                    if (Md5.MD5(oldPassword).equals(su.get("user_pwd"))) {
                        if (su.set("user_pwd", Md5.MD5(password)).update()) {
                            renderJson(JsonResult.getResult(9, "密码修改成功"));
                        } else {
                            renderJson(JsonResult.getResult(9, "密码修改失败"));
                        }
                    } else {
                        renderJson(JsonResult.getResult(9, "旧密码不正确"));
                    }
                }
            }
        } else {
            renderJson(JsonResult.getResult(9, "两次密码不一致"));
        }
    }

    /**
     * 输出 验证码
     */
    @Clear
    public void ValidateCode() {
        try {
            ////120高，40宽，4个数字，10干扰线
            ValidateCode vc = new ValidateCode(120, 40, 4, 10);
            getRequest().getSession().setAttribute("VALIDATECODE", vc.getCode());
            if (DEBUG) System.out.println("验证码：" + vc.getCode());
            vc.write(getResponse().getOutputStream());
            renderNull();
        } catch (Exception e) {
            renderNull();
        }
    }

    /**
     * 输出 随机密码
     */
    @Clear
    public void getRandomPwdApi() {
        renderJson(Jmode.n().set("pwd", Pwd.getRandomPwd()));
    }
}
